package com.tacuati.content;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tacuati.Utils;
import com.tacuati.ui.ContentTreeNode;

public abstract class Item implements Comparable<Item>, ContentTreeNode {
	private String title;
	private String path;
	private String hash;
	private Format format;
	private String author;

	public Item(String path) {
		this.path = path;
		this.author = "";
		this.hash = "";
		this.title = "";
	}
	
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public static Item getItem(String path, Format format) {
		Item i = null;
		switch (format) {
		case MOBI:
			i = new MobiBook(path, Format.MOBI);
			break;
		case AZW:
			i = new MobiBook(path, Format.AZW);
			break;
		case PRC:
			i = new MobiBook(path, Format.PRC);
			break;
		case PDF:
			i = new PdfBook(path);
			break;
		case UNKNOWN:
		default:
			i = new Unknown(path);
			break;
		}
		return i;
	}

	public static Map<String, Item> getItems(String path) {
		Map<String, Item> items = new HashMap<String, Item>();
		List<File> files = Utils.getFiles(new File(path));
		for (File file : files) {
			if (file.isFile()) {
				Format format = Format.getFormat(file.getAbsolutePath());
				if (format.isValidItem()) {
					Item i = Item.getItem(file.getAbsolutePath(), format);
					items.put(i.getHash(), i);
				}
			}
		}
		return items;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getHash() {
		return hash;
	}

	public void setHash(String hash) {
		this.hash = hash;
	}

	public Format getFormat() {
		return format;
	}

	public void setFormat(Format format) {
		this.format = format;
	}

	public abstract String toJson();

	public int compareTo(Item i) {
		return this.getTitle().compareTo(i.getTitle());
	}
	
	public abstract Item copy();
		
	@Override
	public ContentTreeNode getChild(int index) {
		return null;
	}

	@Override
	public int getChildCount() {
		return 0;
	}

	@Override
	public int getIndexOfChild(ContentTreeNode child) {
		return -1;
	}

	@Override
	public String getNodeName() {
		return getTitle();
	}

	@Override
	public void setNodeName(String name) {
		setTitle(name);
	}
	
	@Override
	public void addChild(int index, ContentTreeNode o) {
	}

	@Override
	public void removeChild(int index) {
	}
	
	@Override
	public boolean isEditable() {
		return false;
	}
	
	@Override
	public String getNodeRenderer() {
		return getNodeName();
	}
}
